package registnet.base.source;

import grammar.PrerequisiteCruncher;

import java.util.List;
import java.util.ListIterator;

import registnet.base.Course;
import registnet.base.Curriculum;
import registnet.base.Prerequisite;
import registnet.dao.CurriculumCourse;
import registnet.dao.CurriculumCoursePeer;
import registnet.dao.CurriculumPeer;

/**
 * Defines a class for creating a <code>Curriculum</code> from the data from the database.
 */
public class CurriculumSource implements ICurriculumSource {

	/**
	 * The curriculum.
	 */
	private Curriculum curriculum;
	
	/**
	 * The curriculum code of the curriculum from the database. 
	 */
	private String curriculumCode;
	
	/**
	 * Creates a curriculum from a curriculum from the database with the given curriculum code.
	 * @param curriculumCode
	 */
	public CurriculumSource(String curriculumCode){
		this.curriculumCode = curriculumCode;
		load();
	}
	
	@Override
	public Curriculum getCurriculum() {
		return curriculum;
	}

	@Override
	public Curriculum load() {
		
		if (curriculum != null) return curriculum;
		else curriculum = new Curriculum();
		
		try{
			registnet.dao.Curriculum daoCurriculum = new CurriculumPeer().getCurriculum(curriculumCode);
			
			//curriculumCode
			curriculum.setCurriculumCode(curriculumCode);
			
			//courses
			List<CurriculumCourse> daoCurriculumCourses = new CurriculumCoursePeer().getCurriculumCourses(daoCurriculum.getCurriculumId());
			for(int i=0; i<daoCurriculumCourses.size(); i++){
				CurriculumCourse daoCurriculumCourse = daoCurriculumCourses.get(i);
				registnet.dao.Course daoCourse = daoCurriculumCourse.getCourse();
				
				Course course = new CourseSource(daoCourse.getCourseCode()).getCourse();
				
				//prerequisites
				List<String> prerequisiteList = PrerequisiteCruncher.getPrerequisites(daoCurriculumCourse.getPrerequisite());
				ListIterator<String> temp = prerequisiteList.listIterator();
				while(temp.hasNext()){
					Prerequisite prerequisite = new Prerequisite(temp.next());
					course.addPrerequisite(prerequisite);
				}
				
				//semester
				course.setSemester(daoCurriculumCourse.getSemester());
				
				//year
				course.setYear(daoCurriculumCourse.getYear());
				
				curriculum.addCourse(course);
			}
			
			
		}catch(Exception e){
			System.err.println("****[error] Curriculum("+curriculumCode+") loading failed. "+e.getMessage());
		}
		
		return curriculum;
	}

}
